<?php
/**
* 城市分站类
* @author moufer<moufer@163.com>
* @copyright (C)2001-2007 Moufersoft
*/
!defined('IN_MUDDER') && exit('Access Denied');

class ms_subsite extends ms_base
{
	protected $city = null;

	/**
	 * 检测一个分站(名)是否存在
	 * @param  string  $subsite 分站名
	 * @return boolean             [description]
	 */
	public static function check_exists($subsite)
	{
		$city = ms_city::from_domain($subsite);
		return !empty($city);
	}


	public static function get_url($city_domain_or_id='', $is_city_id = FALSE)
	{
		if(!$city_domain_or_id) return S('siteurl');
		$city = $is_city_id?form_id($city_domain_or_id):ms_city::from_domain($city_domain_or_id);
		if(!$city) return S('siteurl');
		return G('url')->create("city:{$city['aid']}/index", TRUE);
	}

	/**
	 * 获取当前访问的或指定一个城市类
	 * @param  integer $city_id 指定的一个城市ID
	 * @return ms_city
	 */
	public static function create($city_id = null)
	{
		if(!$citys = ms_city::get_citys()) return false;
		//指定了城市ID
		if(!is_null($city_id)) {
			if(isset($citys[$city_id]) && $citys[$city_id]['enabled']) return new self($citys[$city_id]);
			return false;
		}
		//从子域名或者城市目录中获取
		$domain = trim(G('url')->get_subsite());
		if($domain) {
			foreach ($citys as $city) {
				if($city['domain'] == $domain && $city['enabled']) return new self($city);
			}
			return false;
		}
		//从本地cookie记录里获取
		$city_id = _cookie('city_id', null, MF_INT_KEY);
		if($city_id > 0) {
			if(isset($citys[$city_id]) && $citys[$city_id]['enabled']) return new self($citys[$city_id]);
			return false;
		}
	}

	public function __construct($city)
	{
		$this->city = $city;
	}

	public function __get($key)
	{
		if($key == 'city_id') $key = 'aid';
		if(isset($this->city[$key])) return $this->city[$key];
		return null;
	}

	public function fetch_data()
	{
		return $this->city;
	}

	/**
	 * 获取当前分站的完整URL
	 * @return string
	 */
	public function url()
	{
		return U("city:{$this->city_id}/index", true);
	}

	/**
	 * 设置为当前访问的城市
	 */
	public function init()
	{
		//SEO 替换
		foreach(array('sitename', 'meta_keywords', 'meta_description') as $key) {
			if(isset($this->config[$key]) && !empty($this->config[$key])) {
				$val = $this->config[$key];
			} else {
				$val = str_replace('{city}', $this->name, S($key));
			}
			$val && S($key, $val); //覆盖系统的相关设置
		}
		//风格替换
		if($this->templateid > 0) {
			S('templateid', $this->templateid);
		}
		//cookie写入
		set_cookie('city_id', $this->aid, 2592000);
		G('city', $this->fetch_data());

		if(!defined('_NULL_CITYID_')) define('_NULL_CITYID_',"0,$this->aid");

		return true;
	}

}

/** end */